<template>
  <div class="user-manage">
    <!-- 用户列表 -->
    <wrapper-main v-if="pageType === 'list'" :load="load">
      <span slot="main-header">版块管理</span>
      <template slot="main-footer">
        <span class="footer-btn">
          <el-button type="primary" @click="addBtnClick">添加</el-button>
          <el-button @click="deleteBtnClick('part')">批量删除</el-button>
          <el-button @click="deleteBtnClick('all')">全部删除</el-button>
        </span>
        <svt-pagination
          class="user-manage-pagination"
          :totalCount="pageTotalCount"
          @changePageIndex="changePageIndex"
          :currentPage="pageCurrentPage"
        ></svt-pagination>
      </template>
      <checkbox-table
        :startIndex="tableStartIndex"
        :tableHeaderData="tableHeaderData"
        :tableData="tableData"
        @setStyle="setTableColStyle"
        @deleteBtnClick="deleteBtnClick"
        @editBtnClick="editBtnClick"
        @selectionChange="selectionChange"
        align="center"
      ></checkbox-table>
    </wrapper-main>
  </div>
</template>
<script>
export default {
  name: "user-manage",
  props: {},
  data() {
    const validatePhone = (rule, value, callback) => {
      let reg = /^1[345789]\d{9}$/;
      if (value === "" || reg.test(value)) callback();
      else callback(new Error("请输入正确的手机号码"));
    };
    return {
      pageType: "list",
      load: false,
      tableHeaderData: [
        {
          name: "版块名称",
          property: "name"
        }
      ],
      tableData: [],
      selectArray: [],
      editRowId: "",
      sectionName: "",
      pageTotalCount: 0,
      pageCurrentPage: 1,
    };
  },
  computed: {
    role() {
      if (this.$store.state.user) return this.$store.state.user.role;
      else return "";
    },
    userId() {
      if (this.$store.state.user) return this.$store.state.user.id;
      else return "";
    },
    tableStartIndex() {
      return (this.pageCurrentPage - 1) * 10
    }
  },
  created() {
    this.load = true;
    // const param = {
    //   role: this.role,
    //   user_id: this.userId
    // };
    const param = {
      user_id: this.userId,
      page: this.pageCurrentPage,
      len: 10
    };
    this.$http("get", "sectionList", param).then(data => {
      this.load = false;
      this.tableData = data.data;
      this.pageTotalCount = data.total
    });
  },
  mounted() {},
  methods: {
    setTableColStyle(params) {
      if (params.column.label === "电话") params.column.minWidth = 100;
      else if (params.column.label === "地址") params.column.minWidth = 120;
    },
    deleteBtnClick(status) {
      if (status === "part" && this.selectArray.length === 0) return;

      this.$confirm("此操作将永久删除且不可撤销，是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.load = true;
        const param = {};

        if (status === "part") {
          param.id = this.selectArray.join(",");
          if (param.id === "") {
            this.load = false;
            return false;
          }
        } else if (status === "all") {
          param.id = status;
        } else {
          param.id = status.id;
        }

        this.deleteItem(param);
      });
    },
    editBtnClick(row) {
      this.editRowId = row.id;
      this.openBox("edit", row.name);
    },
    selectionChange(selection) {
      const arr = [];
      selection.forEach(d => {
        arr.push(d.id);
      });
      this.selectArray = arr;
    },
    deleteItem(param) {
      this.$http("get", "deleteSectionList", param)
        .then(data => {
          this.load = false;
          if (data === "success") {
            this.notify({ type: "success", message: "删除成功" });
            this.getList();
          } else {
            this.$message.error(data || "删除失败");
          }
        })
        .catch(error => {
          this.load = false;
          this.$message.error(error);
        });
    },
    getList(page = 1) {
      // const param = {
      //   role: this.role,
      //   user_id: this.userId
      // };
      const param = {
        user_id: this.userId,
        page: this.pageCurrentPage,
        len: 10
      };
      this.load = true;

      this.$http("get", "sectionList", param)
        .then(res => {
          this.load = false;
          this.tableData = res.data;
          this.pageTotalCount = res.total
          localStorage.setItem("sectionList", JSON.stringify(this.tableData));
        })
        .catch(error => {
          this.load = false;
          this.$message.error(error);
        });
    },
    // 用户输入弹出框
    openBox(type, val) {
      this.$prompt("请输入版块名称", "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: val,
        inputPlaceholder: "请输入版块名称",
        inputValidator: val => {
          if (val === "") return false;
        },
        inputErrorMessage: "版块名称不可以为空"
      })
        .then(({ value }) => {
          if (val === value) return;
          if (value === null) {
            this.$message({
              type: "warning",
              message: "您没有输入任何内容"
            });
            return;
          }

          this.load = true;
          this.sectionName = value;

          if (type === "add") {
            this.addSectionHandle();
          } else if (type === "edit") {
            this.updateSectionHandle();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    addSectionHandle() {
      const param = {
        name: this.sectionName,
        user_id: this.userId
      };
      this.$http("get", "addSection", param)
        .then(data => {
          this.load = false;
          if (data === "success") {
            this.notify({ type: "success", message: "添加成功" });
            this.pageCurrentPage = 1
            this.getList();
          } else {
            this.$message.error(data || "添加失败");
          }
        })
        .catch(error => {
          this.load = false;
          this.$message.error(error);
        });
    },
    updateSectionHandle() {
      const param = {
        id: this.editRowId,
        name: this.sectionName,
        user_id: this.userId
      };

      this.$http("get", "editSection", param)
        .then(data => {
          this.load = false;
          if (data === "success") {
            this.notify({ type: "success", message: "修改成功" });
            this.pageCurrentPage = 1
            this.getList();
          } else {
            this.$message.error(data || "修改失败");
          }
        })
        .catch(error => {
          this.load = false;
          this.$message.error(error);
        });
    },
    addBtnClick() {
      this.sectionName = "";
      this.openBox("add");
    },
    notify({
      title = "",
      message = "成功",
      type = "",
      showClose = false
    } = {}) {
      this.$notify({
        title: title,
        message: message,
        type: type,
        showClose: showClose
      });
    },
    changePageIndex(index) {
      this.pageCurrentPage = index
    }
  }
};
</script>
<style lang='scss' scoped>
.user-manage {
  width: 100%;
  height: 100%;
  background: #fff;
  .checkbox-table {
    height: 100%;
  }
  .footer-btn {
    flex: 1;
  }
  .user-manage-pagination {
    padding-top: 19px;
  }
}
</style>